package com.example.redpocket.controller;


import com.example.redpocket.configuration.redis.RedisUtil;
import com.example.redpocket.entity.Result;
import com.example.redpocket.service.RedPacketService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@RestController
public class RedPacketController {

    @Autowired
    RedPacketService redPacketService;

    @Autowired
    HttpServletRequest request;

    @Autowired
    RedisUtil redisUtil;

    private final static Logger logger = LoggerFactory.getLogger(RedPacketController.class);

    private static int corePoolSize = Runtime.getRuntime().availableProcessors();
    /**
     * 创建线程池  调整队列数 拒绝服务
     */
    private static ThreadPoolExecutor executor  = new ThreadPoolExecutor(corePoolSize, corePoolSize+1, 10l, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1000));

    @PostMapping("/startTwo")
    public Result startTwo(long redPacketId){
        int num=100;

        CountDownLatch latch=new CountDownLatch(num);
        redisUtil.cacheValue(redPacketId+"-num",10);
        redisUtil.cacheValue(redPacketId+"-money",10);

        for(int i=1;i<=num;i++){
            String userId=String.valueOf(i);
            Runnable r=()->{
                Integer money= (Integer) redisUtil.get(redPacketId+"-money");
                if(money>0){
                    Result result=redPacketService.startGrab(redPacketId,userId);
                    if("500".equals(result.get("code").toString())){
                        logger.info("用户{}手慢了，红包派完了",userId);
                    }else{
                        logger.info("用户{}抢红包成功，金额：{}", userId,result.get("msg"));
                    }
                }else{
                    logger.info("用户{}手慢了，红包派完了",userId);
                }
                latch.countDown();
            };
            executor.execute(r);
        }
        try{
            latch.await();//作用是等所有线程都执行完毕，再执行下面代码
            logger.info("剩余金额：{}",redisUtil.get(redPacketId+"-money"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    return Result.ok();
    }

    @PostMapping("/distributeRedPacket")
    public Result distributeRedPacket(int totalAmount,int totalPacket){

        return redPacketService.saveRedPacket(totalAmount,totalPacket);

    }

    @GetMapping("/grabRedPacket")
    public Result grabRedPacket(){

        String userId=request.getSession().getId();

        Integer redPacketId= (Integer) redisUtil.get("redPacketId");
        Integer money= (Integer) redisUtil.get(redPacketId+"-money");
        Result result=new Result();
        if(money>0){
            result=redPacketService.startGrab(redPacketId,userId);
            if("500".equals(result.get("code").toString())){
                logger.info("用户{}手慢了，红包派完了",userId);
            }else{
                logger.info("用户{}抢红包成功，金额：{}", userId,result.get("msg"));
            }
        }else{
            logger.info("用户{}手慢了，红包派完了",userId);
        }
        logger.info("剩余金额：{}",redisUtil.get(redPacketId+"-money"));
        return Result.ok(result.get("msg"));
    }

}
